package com.cntv.viewmodeldemo.savestate;

import android.os.Bundle;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.SavedStateViewModelFactory;
import androidx.lifecycle.ViewModelProvider;

import com.cntv.viewmodeldemo.R;
import com.cntv.viewmodeldemo.livedata.MyLiveDataViewModel;

/**
 * Created By Mahongyin
 * Date    2020/9/17 14:53
 * ViewModel   livedata 使用
 */
public class SaveStateViewModelActivity extends AppCompatActivity {
    MySavaStateViewModel viewModel;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewmodel);
        viewModel = new ViewModelProvider(this,new SavedStateViewModelFactory(getApplication(),this)).get(MySavaStateViewModel.class);
//        viewModel = new ViewModelProvider(this).get(MySavaStateViewModel.class);
        LiveData<Integer> liveData=viewModel.getNum();
        //观察数据变化
        liveData.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                ((TextView) findViewById(R.id.textView)).setText(String.valueOf(viewModel.getNum().getValue()));
            }});
        ((TextView) findViewById(R.id.textView2)).setText("ViewModel+livedata 使用");
        findViewById(R.id.button).setOnClickListener(v->{viewModel.add(1);});
        findViewById(R.id.button2).setOnClickListener(v->{viewModel.add(-1);});
    }
}
